package com.albaba.designpattern.strategy.text_003;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zx
 * @version 1.0
 * @description 策略工厂
 * @date 2025/2/24 20:25
 */
public class ReceiptHandleStrategyFactory {

    public ReceiptHandleStrategyFactory(){

    }

    // 使用Map集合存储策略信息，彻底消除if .... else
    public static Map<String, ReceiptHandleStrategy> strategyMap;

    public static void init(){
        strategyMap = new HashMap<>();
        // strategyMap.put("MT1101", new MT1101ReceiptStrategy());
        // strategyMap.put("MT2101", new MT2101ReceiptStrategy());

        SAXReader reader = new SAXReader();
        String file = "D:\\DesignPattern\\src\\main\\resources\\config.xml";

        try {
            Document document = reader.read(file);

            Node node = document.selectSingleNode("/config/className");
            String className = node.getText();

            Class<?> aClass = Class.forName(className);
            ReceiptHandleStrategy receiptHandleStrategy = (ReceiptHandleStrategy) aClass.newInstance();
            strategyMap.put("MT1101", receiptHandleStrategy);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }

    // 根据回执类型，获取对应的策略对象
    public static ReceiptHandleStrategy getStrategy(String receiptType){
        return strategyMap.get(receiptType);
    }


}
